<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12" v-if="userInfo.role!=='patient'">
        <el-card shadow="hover">
          <template #header>
            <div class="clearfix">
              <span>基础信息</span>
            </div>
          </template>
          <div class="info">
            <div class="info-image" @click="toggleFileInputStatus()">
              <input ref="fileInput" accept="image/*" @change="onUploadCover" type="file" hidden/>
              <img alt="" :src="userInfo.headImg"/>
              <span class="info-edit">
                                <i class="el-icon-lx-camerafill"></i>
                            </span>
            </div>
            <div class="info-name">
              <!--<i class="el-icon-phone text-light font18"></i>-->
              <span class="text-light font14" style="font-weight: normal">账户/手机号：</span>
              {{ userInfo.phone }}
            </div>
          </div>
        </el-card>

        <el-card class="m_t15" shadow="hover" v-if="!isPatient">
          <template #header>
            <div class="clearfix">
              <span>简介</span>
            </div>
          </template>
          <div>
            <el-input type="textarea" :rows="5" v-model="formData.remarks" placeholder="简介" maxlength="300"
                      show-word-limit></el-input>
          </div>
          <div class="p_t15 row-align-center">
            <el-button type="primary" @click="onSubmitInfo">保存简介</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="clearfix">
              <span>账户编辑</span>
            </div>
          </template>
          <el-form label-width="120px">
            <el-form-item label="账户/手机号：">
              {{ userInfo.phone }}
            </el-form-item>
            <el-form-item label="姓名：">
              <el-input v-model="formData.name" placeholder="请填写姓名"></el-input>
            </el-form-item>
            <el-form-item label="部门：" v-if="!isPatient">
              <el-input v-model="formData.department" placeholder="部门"></el-input>
            </el-form-item>
            <el-form-item label="职称：" v-if="!isPatient">
              <el-input v-model="formData.jobTitle" placeholder="职称"></el-input>
            </el-form-item>
            <el-form-item label="年龄：">
              <el-input-number :min="18" :max="100" v-model="formData.age" placeholder="年龄"></el-input-number>
            </el-form-item>
            <el-form-item label="身份证号：">
              <el-input maxlength="18" v-model="formData.identityNumber" placeholder="身份证号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱：">
              <el-input v-model="formData.email" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item label="家庭住址：" v-if="!isPatient">
              <el-input type="textarea" :rows="4" v-model="formData.address" placeholder="家庭住址"
                        minlength="300"></el-input>
            </el-form-item>
            <el-form-item label="新密码：">
              <el-input type="password" v-model="formData.password" placeholder="填写新密码保存后可修改"></el-input>
            </el-form-item>
            <el-form-item label="确认密码：">
              <el-input type="password" v-model="formData.rePassword" placeholder="填写新密码保存后可修改"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">保存</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {computed, ref, toRaw, watch} from "vue";
import {useStore} from "vuex";
import Patient from "../api/modules/Patient";
import {deepClone, isCard, isEmail, isEmpty} from "../utils/helpers";
import Toast from "../utils/Toast";
import Media from "../api/modules/Media";
import Events from "../events/Events";
import {RoleTypes} from "../hooks/user/useUserLogin";
import Doctor from "../api/modules/Doctor";
import {UploadFilled} from "@element-plus/icons-vue";

export default {
  name: "user",
  components: {
    UploadFilled
  },
  setup() {
    const store = useStore();
    const formData = ref({
      name: "",
      age: "",
      identityNumber: "", // 身份证号
      headImg: "",
      department: "", // 部门
      remarks: "", // 简介
      address: "", // 住址
      jobTitle: "", // 职称
      email: "", // 邮箱
      password: "",
      rePassword: "",

    });
    const fileInput = ref(null);
    const _formData = deepClone(toRaw(formData.value));
    const userInfo = computed(() => store.state.user.userInfo);
    const role = computed(() => store.state.user.role); // 当前登录角色
    const isPatient = computed(() => role.value === RoleTypes.patient); // 当前登录者是否为患者
    watch(() => store.state.user.userInfo, (data) => {
      formData.value = Object.assign({}, _formData, data);
      formData.value.password = '';
    }, {
      immediate: true
    })

    // 保存简介
    async function onSubmitInfo() {
      const _data = deepClone(toRaw(formData.value));
      if (isEmpty(_data.remarks)) {
        Toast.warning('请填写简介');
        return;
      }
      const params = {
        id: _data.id,
        remarks: _data.remarks,
      }
      try {
        if (isPatient.value) { // 患者
          const {message} = await Patient.update(params);
          Toast.success(message);
        } else { // 医生、管理员
          const {message} = await Doctor.update(params);
          Toast.success(message);
        }
        window.emitter.emit(Events.refreshUserInfo, role.value); // 刷新用户信息
      } catch (e) {
        Toast.warning(e.message);
      }

    }

    // 保存用户基本信息
    async function onSubmit() {
      const _data = deepClone(toRaw(formData.value));
      if (isEmpty(_data.name)) {
        Toast.warning('姓名必须填写');
        return;
      }
      if (!isPatient.value && isEmpty(_data.department)) {
        Toast.warning('部门必须填写');
        return;
      }
      if (!isPatient.value && isEmpty(_data.jobTitle)) {
        Toast.warning('职称必须填写');
        return;
      }
      if (!isEmail(_data.email)) {
        Toast.warning('请填写正确的邮箱');
        return;
      }
      if (!isCard(_data.identityNumber)) {
        Toast.warning('请填写正确的身份证号');
        return;
      }
      if (!isPatient.value && isEmpty(_data.address)) {
        Toast.warning('住址必须填写');
        return;
      }

      const params = {
        id: _data.id,
        name: _data.name,
        department: _data.department,
        identityNumber: _data.identityNumber,
        age: _data.age,
        address: _data.address, // 住址
        jobTitle: _data.jobTitle, // 职称
        email: _data.email, // 邮箱
      }
      if (!isEmpty(_data.password)) {
        if (_data.password !== _data.rePassword) {
          Toast.warning('两次输入的密码不相同');
          return;
        }
        params.password = _data.password;
      }
      try {
        if (isPatient.value) { // 患者
          const {message} = await Patient.update(params);
          Toast.success(message);
        } else { // 医生、管理员
          const {message} = await Doctor.update(params);
          Toast.success(message);
        }
        window.emitter.emit(Events.refreshUserInfo, role.value); // 刷新用户信息
      } catch (e) {
        Toast.warning(e.message);
      }
    }


    const toggleFileInputStatus = (val = true) => {
      if (!fileInput.value) {
        return
      }
      if (val) { // 选择文件
        fileInput.value.click();
      } else { // 重置选中的文件
        fileInput.value.value = '';
      }
    };

    function onUploadCover(e) {

      const file = e.target.files[0];
      Media.upload(file).then(async ({data}) => {
        toggleFileInputStatus(false)
        if (!data || !data.url) {
          Toast.warning('图片上传异常');
          return;
        }
        try {
          const params = {
            id: userInfo.value.id,
            headImg: data.url,
          }
          if (isPatient.value) { // 患者
            const {message} = await Patient.update(params);
            Toast.success(message);
          } else { // 医生、管理员
            const {message} = await Doctor.update(params);
            Toast.success(message);
          }
          window.emitter.emit(Events.refreshUserInfo, role.value); // 刷新用户信息
        } catch (e) {
          Toast.warning(e.message);
        }
      }).catch(e => {
        toggleFileInputStatus(false)
        Toast.warning(e.message || '上传失败')
      })

    }

    async function onBeforeUpload(file) {
      Media.upload(file).then(async ({data}) => {
        if (!data || !data.url) {
          Toast.warning('图片上传异常');
          return;
        }
        try {
          const params = {
            id: userInfo.value.id,
            qualifications: data.url,
          }
          if (role.value === RoleTypes.doctor) {
            const {message} = await Doctor.update(params);
            Toast.success(message);
          } else {
            const {message} = await Patient.update(params);
            Toast.success(message);
          }
          window.emitter.emit(Events.refreshUserInfo, role.value); // 刷新用户信息
        } catch (e) {
          Toast.warning(e.message);
        }
      }).catch(e => {
        toggleFileInputStatus(false)
        Toast.warning(e.message || '上传失败')
      })
      // https://element-plus.gitee.io/zh-CN/component/upload.html#drag-to-upload
      return Promise.reject(false); // 阻止le-upload组件的自动上传
    }

    return {
      role,
      isPatient,
      onBeforeUpload,
      fileInput,
      formData,
      userInfo,
      onSubmit,
      onSubmitInfo,
      onUploadCover,
      toggleFileInputStatus,
    };
  },
};
</script>

<style lang="scss" scoped>
.info {
  text-align: center;
  padding: 35px 0;

  .info-name {
    margin: 15px 0 10px;
    font-size: 24px;
    font-weight: 500;
    color: #262626;
  }

  .info-image {
    position: relative;
    margin: auto;
    width: 100px;
    height: 100px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 50px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
    }


    .info-edit {
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      opacity: 0;
      transition: opacity 0.3s ease;

      i {
        color: #eee;
        font-size: 25px;
      }
    }

    &:hover .info-edit {
      opacity: 1;
    }
  }


}


.qualifications {
  width: 100%;
  height: 100%;
}

</style>
